{% extends "terms/base.html" %}

{% block content%}
<div id="keywords"></div>
{% endblock %}

{% block pagination %}
<style>
    #loading {
        transition: opacity 1s ease-out;
        opacity: 1;
    }
</style>

<div id="loading">Loading...</div>

<script>
    async function getData(url, page, paginateBy) {
        const urlWithParams = url + "?" + new URLSearchParams({
            page: page,
            per_page: paginateBy
        })
        const response = await fetch(urlWithParams);
        return response.json();
    }

    class ScrollMorePaginator {
        constructor(perPage) {
            this.perPage = perPage
            this.pageIndex = 1
            this.lastPage = false
            this.container = document.querySelector("#keywords")
            this.elements = document.querySelectorAll("pre")
            this.loader = document.querySelector("#loading")
            this.options = {
                root: null,
                rootMargin: "0px",
                threshold: 0.25
            }
            this.loadMore()
            this.watchIntersection()
        }

        onIntersect() {
            if (!this.lastPage) {
                this.pageIndex++
                this.loadMore()
            }
        }

        addElement(keyword) {
            const pre = document.createElement("pre")
            pre.append(keyword)
            this.container.append(pre)
        }

        watchIntersection() {
            document.addEventListener("DOMContentLoaded", () => {
                const observer = new IntersectionObserver(this.onIntersect.bind(this),
                    this.options);
                observer.observe(this.loader);
            })
        }

        loadMore() {
            getData("{% url 'terms-api' %}", this.pageIndex, this.perPage)
                .then(response => {
                    response.data.forEach((el) => {
                        this.addElement(el.name)
                    });
                    this.loader.style.opacity = !response.page.has_next ? "0" : "1"
                    this.lastPage = !response.page.has_next
                });
        }
    }

    new ScrollMorePaginator(6);
</script>
{% endblock %}
